﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.WinUI.MasterData;
using ESOL.Common.Entity;
using ESOL.Common;
using ESOL.Business.Pur;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Bpt;

namespace ESOL.WinUI.Pur
{
    public partial class frmManagePurchaseOrder : BaseForm.frmBaseMdiBusinessForm
    {
        #region Variable
        private PurPurchaseOrderEntity mSelectedPurchaseOrder;
        #endregion

        #region Constructor
        public frmManagePurchaseOrder()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "PURST", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colCURRENCY, "CS", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colSTATUS, "PURST", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }

        private string GetCondition()
        {
            string condition = "";
            if (txtSupplier.Tag != null && txtSupplier.Tag.GetType() == typeof(MstSupplierEntity))
            {
                MstSupplierEntity supplier = (MstSupplierEntity)txtSupplier.Tag;
                condition += " AND PO.SUPPLIER_ID = '" + supplier.SupplierId + "' ";
            }
            if (string.IsNullOrEmpty(txtPurchaseCode.Text) == false)
            {
                condition += " AND PO.PURCHASE_ORDER_CODE LIKE '%" + txtPurchaseCode.Text + "%'";
            }
            if (txtQuoteOrder.Tag != null && txtQuoteOrder.Tag.GetType() == typeof(PurQuoteOrderEntity))
            {
                PurQuoteOrderEntity quote = (PurQuoteOrderEntity)txtQuoteOrder.Tag;
                condition += " AND PO.PURCHASE_ORDER_ID = '" + quote.QuoteOrderId + "'";
            }
            if (txtDepartment.Tag != null && txtDepartment.Tag.GetType() == typeof(MstDepartmentEntity))
            {
                MstDepartmentEntity entity = (MstDepartmentEntity)txtDepartment.Tag;
                condition += " AND PO.PURCHASE_DEPARTMENT = '" + entity.DepartmentId + "' ";
            }
            if (txtPurchasePerson.Tag != null && txtPurchasePerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                MstPersonEntity entity = (MstPersonEntity)txtPurchasePerson.Tag;
                condition += " AND PO.PURCHASE_PERSON = '" + entity.PersonId + "' ";
            }
            else
            {
                if (!mCanQueryOtherPerson)
                {
                    condition += " AND PO.PURCHASE_PERSON = '" + CommonParameter.CurrentUser.PersonId + "' ";
                }
            }
            if (string.IsNullOrEmpty(cmbStatus.Text) == false && cmbStatus.SelectedValue != null)
            {
                condition += " AND PO.STATUS = '" + cmbStatus.SelectedValue.ToString() + "'";
            }
            if (dtpPurchaseDate.EditValue!=null)
            {
                condition += " AND PO.PURCHASE_DATE >= CONVERT(DATETIME,'" + ((DateTime)dtpPurchaseDate.EditValue).ToString("yyyy-MM-dd") + "')";
            }
            if (dtpPurchaseDateTo.EditValue!=null)
            {
                condition += " AND PO.PURCHASE_DATE <= CONVERT(DATETIME,'" + ((DateTime)dtpPurchaseDateTo.EditValue).ToString("yyyy-MM-dd") + "')";
            }
            if (dtpDeliveryRequiredDate.EditValue!=null)
            {
                condition += " AND PO.DELIVERY_REQUIRED_DATE >= CONVERT(DATETIME,'" + ((DateTime)dtpDeliveryRequiredDate.EditValue).ToString("yyyy-MM-dd") + "')";
            }
            if (dtpDeliveryRequiredDateTo.EditValue!=null)
            {
                condition += " AND PO.DELIVERY_REQUIRED_DATE <= CONVERT(DATETIME,'" + ((DateTime)dtpDeliveryRequiredDateTo.EditValue).ToString("yyyy-MM-dd") + "')";
            }
            return condition;
        }

        private string GetCondition_1()//查询明细
        {
            string condition = "";
            if (string.IsNullOrEmpty(txtProductCode.Text) == false)
            {
                condition += " AND C.PRODUCT_CODE LIKE '%" + txtProductCode.Text + "%'";
            }
            return condition;
        }

        private void BindDataGrid()
        {
            string condition = GetCondition();
            string condition_1 = GetCondition_1();
            string rowCount = txtRowCount.Text;
            string orderBy = "PO.PURCHASE_ORDER_CODE DESC";
            string appId = "";
            if (txtPurApplication.Tag != null && txtPurApplication.Tag.GetType() == typeof(PurApplicationEntity))
            {
                appId = ((PurApplicationEntity)txtPurApplication.Tag).ApplicationId;
            }
            DataTable dt = PurPurchaseOrderBs.GetByCondition(condition, appId, orderBy, rowCount,condition_1);
            gvMain.DataSource = dt;
        }

        private void BindDetailGrid(string purchaseOrderID)
        {
            if (string.IsNullOrEmpty(purchaseOrderID))
            {
                gvDetail.DataSource = null;
                return;
            }
            DataSet ds = PurPurchaseOrderItemBs.GetDataSetByPurchaseOrderID(purchaseOrderID);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvDetail.DataSource = null;
            }
            gvDetail.DataSource = ds.Tables[0];
        }

        private void ResetButtonsEnable()
        {
            btnModify.Enabled = false;
            btnDelete.Enabled = false;
            btnSubmit.Enabled = false;
            btnApprove.Enabled = false;
            btnImport.Enabled = false;
            btnPrint.Enabled = false;
            if (mSelectedPurchaseOrder == null)
            {
                return;
            }
            if (mSelectedPurchaseOrder.Status == PurchaseOrderStatus.PURST01.ToString()
                || mSelectedPurchaseOrder.Status == PurchaseOrderStatus.PURST02.ToString()
                || mSelectedPurchaseOrder.Status == PurchaseOrderStatus.PURST04.ToString())
            {
                btnModify.Enabled = true;
                btnDelete.Enabled = true;
                btnApprove.Enabled = true;
                btnSubmit.Enabled = true;
            }
            else if (mSelectedPurchaseOrder.Status == PurchaseOrderStatus.PURST03.ToString())
            {
                btnImport.Enabled = true;
                btnPrint.Enabled = true;
            }
            else if (mSelectedPurchaseOrder.Status == PurchaseOrderStatus.PURST05.ToString())
            {
                btnPrint.Enabled = true;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            mCanQueryOtherPerson = UICommon.UICommonFunctions.CheckPersonRight(RoleCategory.采购);
            BindComboBox();
            BindDataGrid();
            base.OnShown(e);
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow dr = gridView1.GetDataRow(e.RowHandle);
            mSelectedPurchaseOrder = new PurPurchaseOrderEntity(dr);
            if (mSelectedPurchaseOrder == null)
            {
                return;
            }
            else
            {
                BindDetailGrid(mSelectedPurchaseOrder.PurchaseOrderId);
            }
            ResetButtonsEnable();
        }

        protected override void Click_Query()
        {
            BindDataGrid();
        }

        protected override void Click_View()
        {
            if (mSelectedPurchaseOrder == null)
            {
                MessageBox.Show("请选择一个采购单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainPurchaseOrder frm = new frmMaintainPurchaseOrder();
            frm.ThisActionType = ActionType.View;
            frm.SelectedPurchaseOrder = mSelectedPurchaseOrder;
            frm.ShowDialog();
        }

        protected override void Click_Modify()
        {
            if (mSelectedPurchaseOrder == null)
            {
                MessageBox.Show("请选择一个采购单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainPurchaseOrder frm = new frmMaintainPurchaseOrder();
            frm.ThisActionType = ActionType.Modify;
            frm.SelectedPurchaseOrder = mSelectedPurchaseOrder;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        protected override void Click_New()
        {
            frmMaintainPurchaseOrder frm = new frmMaintainPurchaseOrder();
            frm.ThisActionType = ActionType.New;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        protected override void Click_Delete()
        {
            if (mSelectedPurchaseOrder == null)
            {
                MessageBox.Show("请选择一个采购单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult dr = MessageBox.Show("是否删除选中采购单？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.No)
            {
                return;
            }
            try
            {
                mSelectedPurchaseOrder.Status = PurchaseOrderStatus.PURST09.ToString();
                mSelectedPurchaseOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                mSelectedPurchaseOrder.LastModifiedDate = DateTime.Now;
                bool successful = PurPurchaseOrderBs.UpdatePurPurchaseOrder(mSelectedPurchaseOrder);
                if (successful)
                {
                    MessageBox.Show("删除成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    BindDataGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //询价
        protected override void Click_Submit()
        {
            if (mSelectedPurchaseOrder == null)
            {
                MessageBox.Show("请选择一个采购单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainPurchaseQuoteOrder frm = new frmMaintainPurchaseQuoteOrder(mSelectedPurchaseOrder, null);
            frm.ThisActionType = ActionType.New;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
            /* 送审
            if (mSelectedPurchaseOrder == null)
            {
                MessageBox.Show("请选择一个采购单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult dr = MessageBox.Show("是否送审选中采购单？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.No)
            {
                return;
            }
            try
            {
                mSelectedPurchaseOrder.Status = PurchaseOrderStatus.PURST02.ToString();
                mSelectedPurchaseOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                mSelectedPurchaseOrder.LastModifiedDate = DateTime.Now;
                bool successful = PurPurchaseOrderBs.UpdatePurPurchaseOrder(mSelectedPurchaseOrder);
                if (successful)
                {
                    MessageBox.Show("送审成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    BindDataGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
              */
        }

        protected override void Click_Approve()
        {
            if (mSelectedPurchaseOrder == null)
            {
                MessageBox.Show("请选择一个采购单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainPurchaseOrder frm = new frmMaintainPurchaseOrder();
            frm.ThisActionType = ActionType.Approve;
            frm.SelectedPurchaseOrder = mSelectedPurchaseOrder;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        //订单确认
        protected override void Click_Import()
        {
            if (mSelectedPurchaseOrder == null)
            {
                MessageBox.Show("请选择一个采购单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainPurchaseOrder frm = new frmMaintainPurchaseOrder();
            frm.ThisActionType = ActionType.Confirm;
            frm.SelectedPurchaseOrder = mSelectedPurchaseOrder;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        protected override void Click_Print()
        {
            if (mSelectedPurchaseOrder == null)
            {
                MessageBox.Show("请选择一个采购单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            List<PurPurchaseOrderEntity> list = new List<PurPurchaseOrderEntity>();
            list.Add(mSelectedPurchaseOrder);
            frmPrintFormPurchaseOrder frm = new frmPrintFormPurchaseOrder(list);
            frm.ShowDialog();
        }





        //private void gvDetail_CellContentClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    if (gvDetail.Columns[e.ColumnIndex].Name.Equals("colPRODUCT_CODE"))
        //    {
        //        if (gvDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
        //            return;
        //        string sBlueprintCode = gvDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        //        try
        //        {
        //            EsolWevServices.EsolService ws = new EsolWevServices.EsolService();
        //            byte[] arrFileData = ws.DownloadFile(sBlueprintCode + ".jpg");
        //            Image img = CommonFunctions.byteArrayToImage(arrFileData);
        //            frmProdBlueprintViewer frm = new frmProdBlueprintViewer(img);
        //            frm.ShowDialog();
        //        }
        //        catch (Exception ex)
        //        {
        //            MessageBox.Show("图片不存在！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        }
        //    }
        //}

        private void txtSupplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSupplierQuery frm = new frmMaintainSupplierQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedSupplier != null)
            {
                txtSupplier.Text = frm.SelectedSupplier.SupplierName;
                txtSupplier.Tag = frm.SelectedSupplier;
            }
            else
            {
                txtSupplier.Text = "";
                txtSupplier.Tag = null;
            }
        }

        private void txtQuoteOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainPurchaseQuoteOrderQuery frm = new frmMaintainPurchaseQuoteOrderQuery(false);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPurQuoteOrder != null)
            {
                txtQuoteOrder.Tag = frm.SelectedPurQuoteOrder;
                txtQuoteOrder.Text = frm.SelectedPurQuoteOrder.QuoteOrderCode;
            }
            else
            {
                txtPurApplication.Text = "";
                txtPurApplication.Tag = null;
            }
        }

        private void txtDepartment_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainDepartmentQuery frm = new frmMaintainDepartmentQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedDepartment != null)
            {
                txtDepartment.Text = frm.SelectedDepartment.DepartmentName;
                txtDepartment.Tag = frm.SelectedDepartment;
            }
            else
            {
                txtDepartment.Text = "";
                txtDepartment.Tag = null;
            }
        }

        private void txtPurchasePerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtPurchasePerson.Text = frm.SelectedPerson.NameCn;
                txtPurchasePerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtPurchasePerson.Text = "";
                txtPurchasePerson.Tag = null;
            }
        }

        private void txtPurApplication_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainPurchaseApplicationQuery frm = new frmMaintainPurchaseApplicationQuery(false);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPurApplication != null)
            {
                txtPurApplication.Text = frm.SelectedPurApplication.ApplicationCode;
                txtPurApplication.Tag = frm.SelectedPurApplication;
            }
            else
            {
                txtPurApplication.Text = "";
                txtPurApplication.Tag = null;
            }
        }

        private void txtProductCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                txtProductCode.Text = frm.SelectedProduct.ProductCode;
                txtProductCode.Tag = frm.SelectedProduct;
            }
            else
            {
                txtProductCode.Text = "";
                txtProductCode.Tag = null;
            }
        }

        #endregion
    }
}
